/**
 * Copyright 2009-2010 - YangJiandong(chunquedong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 你可以自由复制、传播本项目的下载包文件，但必须保持其完整性。
 * 我们不用对使用中的风险及由此造成的损失承担任何责任。
 * 详细情况请见《ChunMap许可协议》。

 * 想了解更多有关ChunMap的信息，请访问http://code.google.com/p/chunmap/
 */
package chunmap.model.relate.relateop;

import static chunmap.model.relate.IntersectionMatrix.*;
import chunmap.model.geom.Geometry;
import chunmap.model.geom.Ring;
import chunmap.model.geom.Polygon;
import chunmap.model.relate.ComputeIm;
import chunmap.model.relate.IntersectionMatrix;

/**
 * @author chunquedong
 * 
 */
public class Polygon_Polygon extends ComputeIm {

	public Polygon_Polygon(Polygon a1, Polygon a2) {
		g1 = a1;
		g2 = a2;
	}

	@Override
	protected int inner2innerDim(Geometry g1, Geometry g2) {
		Polygon a1 = (Polygon) g1;
		Polygon a2 = (Polygon) g2;
		ComputeIm r2r = new LinearRing_LinearRing(a1.getShell(), a2
				.getShell());
		IntersectionMatrix tim = r2r.getIM();
		if (tim.get(Inner, Inner) != EmptyDim) {
			if (!inHoles(a1.getShell(), a2) && !inHoles(a2.getShell(), a1))
				return AreaDim;
		}
		return EmptyDim;
	}

	/**
	 * @param a1
	 * @param a2
	 */
	private boolean inHoles(Ring r1, Polygon a2) {
		for (Ring r2 : a2.getHoles()) {
			if (r2.containLineStringIn(r1))
				return true;
		}
		return false;
	}

	@Override
	protected boolean within(Geometry g1, Geometry g2) {
		if (im.get(Inner, Inner) == EmptyDim)
			return false;

		Polygon a1 = (Polygon) g1;
		Polygon a2 = (Polygon) g2;
		ComputeIm r2r = new LinearRing_LinearRing(a1.getShell(), a2
				.getShell());
		IntersectionMatrix tim = r2r.getIM();

		if (tim.get(Inner, Outer) != EmptyDim)
			return false;

		for (Ring r2 : a2.getHoles()) {
			ComputeIm r2r2 = new LinearRing_LinearRing(a1.getShell(), r2);
			IntersectionMatrix tim2 = r2r2.getIM();
			if (tim2.get(Inner, Inner) != EmptyDim)
				if (inHoles(r2, a1))
					return false;
		}

		return true;
	}
}
